package com.example.project3.controller;

import com.example.project3.entity.User;
import com.example.project3.service.impl.UserServiceImpl;
import com.example.project3.util.API;
import com.example.project3.util.MyJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    private UserServiceImpl userServiceImpl;
    private MyJWT myJWT;

    @PostMapping("/sendCode")
    public API sendCode(@RequestParam String email) {
        userServiceImpl.sendCode(email);
        return API.success();
    }

    // 验证验证码接口
    @PostMapping("/verification")
    public API verificationCode(@RequestParam String email, @RequestParam String code) {
        userServiceImpl.verifyCode(email, code.toUpperCase());
        return API.success();
    }

    //注册接口
    @PostMapping("/register")
    public API registerEmail(@RequestBody User user) {
        userServiceImpl.register(user);
        return API.success();
    }

    //登录接口
    @RequestMapping("/login")
    public API login(@RequestBody User user) {
        String token = userServiceImpl.login(user);
        return API.success(token);
    }

    @GetMapping("/info")
    public API getMyInfo(HttpServletRequest request) {
        Integer uid = myJWT.getUid(request);
        User user = userServiceImpl.getById(uid);
        user.setPassword("");
        return API.success(user);
    }

    //修改用户名接口
    @PostMapping("/updateNickname")
    public API change(@RequestBody User user) {
        userServiceImpl.updateUsername(user);
        return API.success();
    }

    @Autowired
    public void setUserServiceImpl(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }


    @Autowired
    public void setMyJWT(MyJWT myJWT) {
        this.myJWT = myJWT;
    }
}
